/**
 * Copyright (c) 2011 Baidu.com, Inc. All Rights Reserved
 */
package net.dreamlu.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.baidu.bae.api.fetchurl.BaeFetchurl;
import com.baidu.bae.api.fetchurl.BaeFetchurlFactory;
import com.baidu.bae.api.fetchurl.BasicNameValuePair;
import com.baidu.bae.api.fetchurl.NameValuePair;

/**
 * 进行http访问的基本类
 * 
 * @author chenhetong(chenhetong@baidu.com)
 * 
 */
public class HttpUtil {

	private static final Logger log = Logger.getLogger(HttpUtil.class);
	
	private static final String DEFAULT_CHARSET = "UTF-8";

	public static final String METHOD_POST = "POST";

	public static final String METHOD_GET = "GET";

	public static final int HTTPSTATUS_OK = 200;

	public static final int CONNECTIMEOUT = 5000;

	public static final int READTIMEOUT = 5000;

	/**
	 * 通过get方法访问，默认编码为utf-8
	 * 
	 * @param url
	 *            访问的url地址
	 * @return 返回请求响应的数据
	 * @throws IOException
	 */
	public static String doGet(String url) {
		return doGet(url, null, DEFAULT_CHARSET);
	}
	
	/**
	 * 通过get方法访问，默认编码为utf-8
	 * 
	 * @param url
	 *            访问的url地址
	 * @param params
	 *            请求需要的参数
	 * @return 返回请求响应的数据
	 * @throws IOException
	 */
	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params, DEFAULT_CHARSET);
	}

	/**
	 * 通过get方法访问
	 * 
	 * @param url
	 *            访问的url地址
	 * @param params
	 *            请求需要的参数
	 * @param charset
	 *            字符编码
	 * @return 返回请求响应的数据
	 * @throws IOException
	 */
	public static String doGet(String url, Map<String, String> params, String charset){
		if (StringUtils.isEmpty(url)) {
			return null;
		}
		String response = null;
		if(null != params && !params.isEmpty()){
			url += "?" + buildQuery(params, charset);
		}
		BaeFetchurl fetchUrl = BaeFetchurlFactory.getBaeFetchurl();
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		fetchUrl.setHeader("Content-Type", ctype);
		fetchUrl.setHeader("User-Agent", "baidu-restclient-java-bae-1.0");
		fetchUrl.get(url);
		int httpCode = fetchUrl.getHttpCode();
		if (httpCode == HTTPSTATUS_OK) {
			response = fetchUrl.getResponseBody();
		}else {
			log.error(fetchUrl.getErrmsg());
		}
		return response;

	}

	public static String doPost(String url, Map<String, String> params) {
		return doPost(url, params, CONNECTIMEOUT, READTIMEOUT);
	}

	/**
	 * 
	 * 通过post方法请求数据，默认字符编码为utf-8
	 * 
	 * @param url
	 *            请求的url地址
	 * @param params
	 *            请求的参数
	 * @param connectTimeOut
	 *            请求连接过期时间
	 * @param readTimeOut
	 *            请求读取过期时间
	 * @return 请求响应
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params,
			int connectTimeOut, int readTimeOut) {
		return doPost(url, params, DEFAULT_CHARSET, connectTimeOut, readTimeOut);
	}

	/**
	 * 
	 * 通过post方法请求数据
	 * 
	 * @param url
	 *            请求的url地址
	 * @param params
	 *            请求的参数
	 * @param charset
	 *            字符编码格式
	 * @param connectTimeOut
	 *            请求连接过期时间
	 * @param readTimeOut
	 *            请求读取过期时间
	 * @return 请求响应
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params,
			String charset, int connectTimeOut, int readTimeOut) {
		String response = null;
		List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
		for (Entry<String, String> entry : params.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
				paramsList.add(new BasicNameValuePair(key, value));
			}
		}
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		BaeFetchurl fetchUrl = BaeFetchurlFactory.getBaeFetchurl();
		fetchUrl.setConnectTimeout(connectTimeOut);
		fetchUrl.setReadTimeout(readTimeOut);
		fetchUrl.setHeader("Content-Type", ctype);
		fetchUrl.setHeader("User-Agent", "baidu-restclient-java-bae-1.0");
		fetchUrl.setPostData(paramsList, charset);
		fetchUrl.post(url);
		int httpCode = fetchUrl.getHttpCode();
		if (httpCode == HTTPSTATUS_OK) {
			response = fetchUrl.getResponseBody();
		} else {
			log.error(fetchUrl.getErrmsg());
		}
		return response;
	}

	/**
	 * 
	 * @param params
	 *            请求参数
	 * @return 构建query
	 */
	public static String buildQuery(Map<String, String> params, String charset) {
		if (params == null || params.isEmpty()) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (Entry<String, String> entry : params.entrySet()) {
			if (first) {
				first = false;
			} else {
				sb.append("&");
			}
			String key = entry.getKey();
			String value = entry.getValue();
			if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
				try {
					sb.append(key).append("=").append(URLEncoder.encode(value, charset));
				} catch (UnsupportedEncodingException e) {
					log.error(e);
				}
			}
		}
		return sb.toString();
	}
}